package com.ww.sound_emission.controller;

import com.ww.sound_emission.service.MinioUploadsService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;


@RequestMapping("/uploads")
@RestController
@CrossOrigin
public class FileUploadController {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return "文件不能为空";
            }

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传文件到 MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName) // 桶名称
                            .object(file.getOriginalFilename()) // 文件名
                            .stream(inputStream, file.getSize(), -1) // 文件流和大小
                            .contentType(file.getContentType()) // 文件类型
                            .build()
            );

            return "文件上传成功: " + file.getOriginalFilename();
        } catch (MinioException e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        }
    }








    @Autowired
    private MinioUploadsService minioService;

    /**
     * 列出 Bucket 中的所有文件
     */
    @GetMapping("/files")
    public List<String> listFiles() {
        return minioService.listFiles();
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名称
     */
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String fileName) {
        InputStream inputStream = minioService.downloadFile(fileName);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }

    /**
     * 获取文件的 Presigned URL
     *
     * @param fileName 文件名称
     * @param expiry   过期时间（单位：秒）
     */
    @GetMapping("/presigned-url")
    public String getPresignedUrl(@RequestParam String fileName) {
        return minioService.getPresignedUrl(fileName);
    }






















}